/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Classes;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author ward
 */
public class OpenPlayProjectList extends HttpServlet
{

    AE.VarParams varParams;
    AE.DataConsolidation dc;
    AE.MyListString projectItems;    
    AE.Data analysisProject;
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {

        // this is to be an entry in the web.xml file that points to a drive/subdir
        // where variables.config and license.config reside
        String FullySpecifiedPathToBaseDirectoryOfFiles =
                getServletContext().getInitParameter( "OpenPlayProjectList" );

        String sessionId = request.getSession().getId();

        PrintWriter out = null;
        try
        {
            out = response.getWriter();
            if( out != null )
            {
                String errMsg = Init( FullySpecifiedPathToBaseDirectoryOfFiles, sessionId );
                if( errMsg != null )
                    out.write( errMsg );
                else
                {
                    out.println( HelperHtml.GetHead() );
                    out.println( "<body>" );
                    
                    String projectFileName = request.getParameter( "file" );
                    if( projectFileName != null )
                    {
                        RunProjectFileToHtml( out, projectFileName );
                    }
                    else
                    {
                        String scriptCommands[] = request.getParameterValues("scriptCommands");
                        if( scriptCommands != null )
                        {
                            RunScriptCommandsToHtml( out, scriptCommands );
                        }
                        else
                        {
                            RunAllProjectFilesToHtml( out );
                        }
                    }
                    out.println( "</body>" );
                }
            }
        } catch( Exception e )
        {
            if( out != null )
                out.print( e.getLocalizedMessage() );
        } finally
        {
            if( out != null )
                out.close();
        }
    }

    public void RunAllProjectFilesToHtml( PrintWriter out )
    {
        AE.MyListString filelist = AE.MyDirectory.GetFiles( varParams.GetMyProjectsDir() );

        for( int projectIndex = 0,  projectCount = filelist.GetCount() ;
                projectIndex < projectCount ; projectIndex++ )
        {
            String projectFileName = filelist.Get( projectIndex );
            if( projectFileName.startsWith( "_" ) == false )
            {
                RunProjectFileToHtml( out, projectFileName );
            }
        }
    }

    private void RunProjectFileToHtml( PrintWriter out, String projectFileName )
    {
        String error = LoadProjectFromProjectFile( projectFileName );
        if( error != null )
            out.print( "There was a problem building this project. " + error );
        
        else
        {
            error = ExecuteProjectLines();
            if( error != null )
                out.print( error );
            else
                OutputHtml.RunExecutedProjectToHtml( out, projectFileName, analysisProject );
        }
    }

    private void RunScriptCommandsToHtml( PrintWriter out, String [] scriptCommands )
    {
        projectItems = new AE.MyListString( scriptCommands );
        String error = ExecuteProjectLines();
        if( error != null )
            out.print( error );
        else
            OutputHtml.RunExecutedProjectToHtml( out, null, analysisProject );
    }
    
    public String LoadProjectFromProjectFile( String projectFileName )
    {
        if( projectFileName == null || projectFileName.length() == 0 )
        {
            return "Invalid project filename";
        }
        
        String fullProjectFileName = varParams.GetMyProjectsDir() + projectFileName;
        if( AE.MyFile.Exists( fullProjectFileName ) == false )
        {
            return fullProjectFileName + " not found";
        } 
        
        projectItems = AE.MyFile.ReadAllLines( varParams, fullProjectFileName );
        if( projectItems == null || projectItems.GetCount() == 0 )
            return "problem with contents of " + fullProjectFileName;
        else
            return null;
    }

    private String ExecuteProjectLines()
    {
        analysisProject = new AE.Data();
        if( analysisProject == null )
            return "Failed to load, probably low memory or corrupted files" ;

        for( Integer i=0, count = projectItems.GetCount() ; i < count ; i++ )
        {
            String scriptItem = projectItems.Get( i );
            String message = ExecuteLine( scriptItem ) ;
            if( message != null )
                return "Line " + i.toString() + message ;
        }
        return null;    // a return value of null means success 
    }
    
    private String ExecuteLine( String scriptItem )
    {
        boolean success = dc.RunScript( scriptItem, analysisProject, true );
        if( success == false )
            return " failed: " + scriptItem;
        else
            return null;
    }

    public String Init( String variablesPath, String sessionId )
    {
        varParams = new AE.VarParams();
        if( varParams == null )
            return "Failed to load, probably low memory or corrupted files" ;

        String errMsg = varParams.ReadFile( variablesPath, sessionId );
        if( errMsg != null )
            return errMsg;

        dc = new AE.DataConsolidation( varParams );

        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        processRequest( request, response );
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        processRequest( request, response );
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo()
    {
        return "Short description";
    }
    // </editor-fold>
}
